import { useEffect, useState, type MouseEvent } from "react";
import network from "../../utils/network";
import { Button, Input, message, Modal } from "antd";
import { DeleteFilled } from '@ant-design/icons';
const { confirm } = Modal;
export default ({ plan, Get, stationKey }: { plan: string, Get: () => void , stationKey: string}) => {
    const [dataSource, setDataSource] = useState<any[]>([]);
    useEffect(() => {
        GetData();
    }, [])

    // 更新清空数据

    const GetData = async () => {
        setDataSource([]);
        const res = await network(`http://127.0.0.1:5005/api/custRule/getRulesGroupByPlan/${plan}`);
        setDataSource(res.data.result)
    }
    function HandleInputChange(index: number, key: string, value: string) {
        dataSource[index][key] = value;
        setDataSource([...dataSource])
    }
    const HandleDeleteClick = async (e: MouseEvent, index: number, item: any) => {
        e.preventDefault()
        e.stopPropagation()
        if (!dataSource[index].id) {
            dataSource.splice(index, 1);
            setDataSource([...dataSource]);
            message.success("删除成功");
            return
        }
        // network(`http://127.0.0.1:5005/api/custRuleData/getCustRuleDatas?plan=${item.plan}`)
        confirm({
            title: '删除规则选项',
            icon: <DeleteFilled />,
            content: <div>删除序号为: <span className="text-2xl font-bold text-green-400">{index + 1}</span > 名称为: <span className="text-2xl font-bold text-green-400">{item.ruleName}</span> 的规则项</div>,
            // content: `删除序号为: ${index + 1} 名称为:   ${item.ruleName}  的规则项?`,
            async onOk() {
                // delete api
              
                const res = await network("http://127.0.0.1:5005/api/custRule/by-id?id=" + dataSource[index].id, {}, "DELETE")
                if (!res.data.result) {
                    message.warning("删除失败!");
                    return;
                }
                dataSource.splice(index, 1);
                setDataSource([...dataSource]);
                message.success("删除成功");
                GetData();
                Get();
            },
            onCancel() {
                message.info("取消删除");
            },
        });

    }
    return <div className="relative h-full">
        <ul className="pb-10">
            {
                dataSource.map((item: any, index: number) => {
                    return <li className="shadow-2xl flex  mb-2 gap-4 items-center" key={index}>
                        <div
                            onDoubleClick={(e) => HandleDeleteClick(e, index, item)} className="w-10 font-bold select-none text-center cursor-pointer">{index + 1}</div>
                        <Input onInput={(t) => HandleInputChange(index, "ruleName", t.currentTarget.value)} allowClear
                            value={dataSource[index]["ruleName"]} addonBefore="规则名称" placeholder="请输入规则名称"></Input>
                           
                            {
                                plan != "上线工位名称配方" && <>
                                    
                        <Input onInput={(t) => HandleInputChange(index, "ruleContent", t.currentTarget.value)} allowClear
                            value={dataSource[index]["ruleContent"]} addonBefore="规则内容" placeholder="请输入规则内容"></Input>
                        <Input onInput={(t) => HandleInputChange(index, "ruleLength", t.currentTarget.value)} allowClear
                            value={dataSource[index]["ruleLength"]} addonBefore="规则长度" placeholder="请输入规则长度"></Input>
                        <Button disabled={plan == "上线工位名称配方"} onClick={(e) => HandleDeleteClick(e, index, item)} type="primary" danger shape="circle" icon={<DeleteFilled />} />
                                </> 
                            }
                    </li>
                })
            }
        </ul>
        <div className="flex gap-3 fixed bottom-10 bg-white">
            <Button disabled={plan == "上线工位名称配方"} className="px-10!" color="green" onClick={() => {
                if (dataSource.length >= 20) {
                    message.warning("最多增加20个");
                    return
                }
                setDataSource([...dataSource, {
                    id: 0,
                    rulePlan: plan,
                    ruleName: "",
                    ruleContent: "",
                    ruleLength: "",
                    ruleUse: ""
                }])
            }} variant="solid">增加</Button>
            <Button className="px-10!" onClick={async () => {
                for (let index = 0; index < dataSource.length; index++) {
                    const item = dataSource[index];
                    console.log("item", item);
                    if (!item.ruleName || !item.ruleContent || !item.ruleLength) {
                        message.warning((index + 1) + "号  请把规则全填写完成 或 双击序号删除!");
                        return;
                    }
                    if (!/^[\d]+$/.test(item.ruleLength)) {
                        message.warning((index + 1) + "号的     规则长度          请检查是否是数字!");
                        return;
                    }
                    if (!/^[a-zA-Z\d-]+$/.test(item.ruleContent)) {
                        message.warning((index + 1) + "号的     规则内容          请检查是否是英文或数字!");
                        return;
                    }
                }
                const addData = dataSource.filter(item => !item.id)
                const updateData = dataSource.filter(item => item.id)
                // 生成数据
                addData.forEach(async (item) => {
                    const res = await network(
                        "http://127.0.0.1:5005/api/custRule/setRule",
                        item, "POST")
                    if (res.data.code == 500) {
                        message.error(res.data.message)
                        return;
                    }
                    if (!res.data.result) {
                        message.error(res.data.message + "   数据库新增失败!")
                        return;
                    }
                })
                // 更新数据
                const res = await network(
                    "http://127.0.0.1:5005/api/custRule/patchFullRulesById",
                    updateData,
                    "PATCH")

                if (res.data.code == 500) {
                    message.error(res.data.message)
                    return;
                }
                if (!res.data.result) {
                    message.error(res.data.message + "   数据库更新失败!")
                    return;
                }
                message.success("更新成功了!");
                GetData();
            }} type="primary">更新</Button>
            <Button className="px-10!" onClick={async () => {
                if(stationKey != "New001" && plan == "上线工位名称配方" 

                 ) {
                    message.warning("该配方只能下发到  1 工位");
                    return;
                }
                if(stationKey == "New001" && plan != "上线工位名称配方") {
                    message.warning("1 工位 只接受  上线工位名称配方  的下发" );
                    return;
                }
                // patch api
                for (let index = 0; index < dataSource.length; index++) {
                    const item = dataSource[index];
                    if (!item.ruleName || !item.ruleContent || !item.ruleLength) {
                        message.warning((index + 1) + "号  请把规则全填写完成 或 双击序号删除!");
                        return;
                    }
                    if (!/^[\d]+$/.test(item.ruleLength)) {
                        message.warning((index + 1) + "号的     规则长度          请检查是否是数字!");
                        return;
                    }
                    if (!/^[a-zA-Z\d-]+$/.test(item.ruleContent)) {
                        message.warning((index + 1) + "号的     规则内容          请检查是否是英文或数字!");
                        return;
                    }
                }
                const res = await network(`http://127.0.0.1:5005/api/custRule/patchDownloadRulesByPlan/${plan}?station=${stationKey}`, {}, "PATCH")
                if (res.data.code == 500) {
                    message.error(res.data.message)
                    return;
                }
                if (!res.data.result) {
                    message.error(res.data.message + "   数据库更新失败!")
                    return;
                }
                message.success("下发成功!");
            }} color="pink" variant="solid">下发</Button>
        </div>
    </div>
}